package com.jspgou.cms.action.admin.main;

import static com.jspgou.common.page.SimplePage.cpn;

import java.sql.Date;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jspgou.common.page.Pagination;
import com.jspgou.common.web.CookieUtils;

import com.jspgou.core.entity.Member;
import com.jspgou.core.entity.User;
import com.jspgou.core.entity.Website;
import com.jspgou.core.manager.MemberMng;
import com.jspgou.core.manager.UserMng;
import com.jspgou.core.web.SiteUtils;
import com.jspgou.core.web.WebErrors;
import com.jspgou.cms.entity.ConsumerTop;
import com.jspgou.cms.entity.Order;
import com.jspgou.cms.manager.ConsumerTopMng;
import com.jspgou.cms.manager.OrderMng;

@Controller
public class ConsumerTopAct {
	private static final Logger log = LoggerFactory
			.getLogger(ConsumerTopAct.class);

	@RequestMapping("/consumertop/v_list.do")
	public String list(ConsumerTop bean, Long[] userIds, Long[] memberIds,
			Integer pageNo, HttpServletRequest request, ModelMap model) {
		Pagination pagination = memberMng.getPage(cpn(pageNo),
				CookieUtils.getPageSize(request), 1);
		List<User> users = userMng.getList(userIds);
		Map<String, Double> userTotals = new HashMap<String, Double>();
		for (User user : users) {
			List<Order> orders = orderMng.getList1(memberIds);
			List<Member> members = memberMng.getList(memberIds);
			for (Member member : members) {
				Double money = 0.0;
				Long memberId = member.getId();
				for (Order order : orders) {
					if (order.getMember().getId() == memberId) {
						money = money + order.getTotal();
						member.setTotal(money);
					}
				}
				memberMng.update(member);
				userTotals.put(member.getId().toString(), money);
			}
		}

		model.addAttribute("userTotals", userTotals);
		model.addAttribute("users", users);
		model.addAttribute("pagination", pagination);
		model.addAttribute("pageNo", pageNo);
		List<Object> orders = orderMng.getTotalOrder();
		model.addAttribute("orders", orders);

		return "consumertop/list";
	}
     /**
      * 
      * @param pageNo
      * @param pageSize
      * @param request   按时间段的搜索会员消费情况
      * @param model
      * @param startTime
      * @param endTime
      * @return
      */
	@RequestMapping(value = "/consumertop/refer.do", method = RequestMethod.POST)
	public String consumerTopList(Integer pageNo, Integer pageSize,
			HttpServletRequest request, ModelMap model, Date startTime,
			Date endTime) {
		Map<String, Double> userTotals = new HashMap<String, Double>();
		List<Order> orders = orderMng.getList(null, null, null, null, null,null,
				null, null, null, startTime, endTime, null, null);
		Long[] ids = new Long[orders.size()];
		for (int i = 0; i < orders.size(); i++) {
			ids[i] = orders.get(i).getMember().getId();
		}

		List<Member> members = memberMng.getList(ids);
		for (Member member : members) {
			userTotals.put(member.getId().toString(), member.getTotal());
			model.addAttribute("userTotals", userTotals);
		}

		Pagination pagination = memberMng.getPage(cpn(pageNo),
				CookieUtils.getPageSize(request), 1);

		model.addAttribute("pagination", pagination);

		return "consumertop/list";
	}

	@RequestMapping("/consumertop/v_add.do")
	public String add(ModelMap model) {
		return "consumertop/add";
	}

	@RequestMapping("/consumertop/v_edit.do")
	public String edit(Long id, Integer pageNo, HttpServletRequest request,
			ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		model.addAttribute("consumerTop", manager.findById(id));
		model.addAttribute("pageNo", pageNo);
		return "consumertop/edit";
	}

	@RequestMapping("/consumertop/o_save.do")
	public String save(ConsumerTop bean, HttpServletRequest request,
			ModelMap model) {
		WebErrors errors = validateSave(bean, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		bean = manager.save(bean);
		log.info("save ConsumerTop id={}", bean.getId());
		return "redirect:v_list.do";
	}

	@RequestMapping("/consumertop/o_update.do")
	public String update(Long userId, Long orderId, ConsumerTop bean,
			Integer pageNo, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateUpdate(bean.getId(), request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		bean = manager.update(bean);
		log.info("update ConsumerTop id={}.", bean.getId());
		return list(null, null, null, pageNo, request, model);
	}

	private WebErrors validateUpdate(Integer id, HttpServletRequest request) {

		return null;
	}

	@RequestMapping("/consumertop/o_delete.do")
	public String delete(Long[] ids, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateDelete(ids, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		ConsumerTop[] beans = manager.deleteByIds(ids);
		for (ConsumerTop bean : beans) {
			log.info("delete ConsumerTop id={}", bean.getId());
		}
		return list(null, null, null, pageNo, request, model);
	}

	private WebErrors validateSave(ConsumerTop bean, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		Website web = SiteUtils.getWeb(request);
		/* bean.setWebsite(web); */
		return errors;
	}

	private WebErrors validateEdit(Long id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		Website web = SiteUtils.getWeb(request);
		if (vldExist(id, web.getId(), errors)) {
			return errors;
		}
		return errors;
	}

	private WebErrors validateUpdate(Long id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		Website web = SiteUtils.getWeb(request);
		if (vldExist(id, web.getId(), errors)) {
			return errors;
		}
		return errors;
	}

	private WebErrors validateDelete(Long[] ids, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		Website web = SiteUtils.getWeb(request);
		errors.ifEmpty(ids, "ids");
		for (Long id : ids) {
			vldExist(id, web.getId(), errors);
		}
		return errors;
	}

	private boolean vldExist(Long id, Long webId, WebErrors errors) {
		if (errors.ifNull(id, "id")) {
			return true;
		}
		ConsumerTop entity = manager.findById(id);
		if (errors.ifNotExist(entity, ConsumerTop.class, id)) {
			return true;
		}
		/*
		 * if (!entity.getWebsite().getId().equals(webId)) {
		 * errors.notInWeb(ConsumerTop.class, id); return true; }
		 */
		return false;
	}

	@Autowired
	private ConsumerTopMng manager;
	@Autowired
	private UserMng userMng;
	@Autowired
	private OrderMng orderMng;
	@Autowired
	private MemberMng memberMng;
}